'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async index() {
    const { ctx } = this;

    
  console.log(this.config)
    /*
      query: get传值
      params: 动态路由传值
      request.body: post传值
    */ 
    const { query, params, request } = ctx

    console.log(query);
    console.log(params);

    /*
      获取service的数this.service.据
    */ 
   const data = await this.service.user.getUser()

    /*
      extend 拓展，封装自己的方法
      application => this.app
      context => this.ctx
    */ 
    ctx.body = query;
    // this.ctx.redirect('/api')
  }
  // 根据jscode解析出openid
  async code() {
    const { ctx } = this;
    const { code } = ctx.request.body
    // AppSecret(小程序密钥) aec6542f58d110224cfdd82244f11224
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=wxb5b6cf44bdca529a&secret=aec6542f58d110224cfdd82244f11224&js_code=${code}&grant_type=authorization_code`
    const res = await ctx.curl(url)
    ctx.body = res.data.toString()
  }

  // 微信登录
  async login() {
    const { ctx } = this;
    const { openid } = ctx.request.body
    // openID，用户唯一标识，注册用，sessionKey，解密用户信息用
    try {
      const findRes = await this.service.user.find({ openid })

      // 如果根据openid没查到用户，就创建用户
      if (!findRes[0]) {
        // 新建预计数据表，绑定openid
        const exp = await this.service.exp.add({ openid })
        // 新建用户
        await this.service.user.create({ expectData: exp._id, openid})
      }
    } catch (error) {
      ctx.body =  { status: 500, message: '服务器异常，请稍后重试' }
    }
    const token = this.app.jwt.sign({
      exp: Math.floor(Date.now() / 1000 + (60 * 60 * 24 * 30)), // 设置过期时间
      'openid': openid, //需要存储的 token 数据
    },  this.app.config.jwt.secret );

    ctx.body =  { token }
  }
  // 保存用户的预计数据
  async saveUserExpectData () {
    const { ctx } = this;
    const { body } = ctx.request
    const { openid } = ctx.state.user
    try {
      let data = await this.service.exp.update(openid, body)
      ctx.body = {
        status: 200,
        message: 'success'
      }
    } catch (error) {
      ctx.body = {
        status: 500,
        message: error,
      }
    }
  }
  // 获取用户的预计数据
  async getUserExpectData() {
    const { ctx } = this;
    const { openid } = ctx.state.user
    try {
      let data = await this.service.exp.find({ openid })
      ctx.body = {
        status: 200,
        message: 'success',
        data
      }
    } catch (error) {
      ctx.body = {
        status: 200,
        message: error,
        data:  null
      }
    }

    
  }
  // 验证token是否过期
  async checkToken() {
    const { ctx } = this;
    // console.log(ctx.state.user);
    ctx.status = 200;
    ctx.body =  { message: 'success', status: 200 }
  }
}

module.exports = HomeController;
